package cloud.pangui.core.mongo.operate;

import cloud.pangui.core.mongo.element.Cond;
import org.bson.Document;

/**
 * @Auther hepangui
 * @Date 2020/10/06 0001
*/
public class Update {


	/**
	 * 条件
	 */
	protected Where where;

	/**
	 * 查询的是哪个表
	 */
	protected String collectionName;


	/**
	 * 属性set的doc
	 */
	protected Document sDoc;


	protected Update() {

	}

	/**
	 * 设置表名
	 *
	 * @param fromName
	 * @return
	 */
	public static Update from(String fromName) {
		Update update = new Update();
		update.collectionName = fromName;
		return update;
	}

	public static Update fromSql(String sql) {
		SqlUpdate sqlUpdate = new SqlUpdate(sql);
		return sqlUpdate;
	}

	/**
	 * 设置对象
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public Update set(String key, Object value) {
		if (sDoc == null) {
			sDoc = new Document();
		}
		Document $set = (Document) sDoc.get("$set");
		if ($set == null) {
			$set = new Document();
			sDoc.put("$set", $set);
		}
		$set.put(key, value);
		return this;
	}

	/**
	 * 自增一个值
	 *
	 * @param key
	 * @param value
	 * @return
	 */
	public Update incr(String key, int value) {
		if (sDoc == null) {
			sDoc = new Document();
		}
		Document $inc = (Document) sDoc.get("$inc");
		if ($inc == null) {
			$inc = new Document();
			sDoc.put("$inc", $inc);
		}
		$inc.put(key, value);
		return this;
	}

	/**
	 * @param conds
	 * @return
	 */
	public Update where(Cond... conds) {
		this.where = new Where(Where.SIMPLE_MODE);
		if (conds != null) {
			this.where.and(conds);
		}
		return this;
	}

	/**
	 * 自定义查询条件
	 *
	 * @param where
	 * @return
	 */
	public Update where(Where where) {
		this.where = where;
		if (where.getMode() != Where.SIMPLE_MODE) {
			throw new Where.CondNotSupportInSimpleModeException("update时只允许使用简单查询条件");
		}
		return this;
	}


	public String getCollectionName() {
		return collectionName;
	}

	public Document getWhereDoc() {
		return where.build();
	}

	public Document getSetDoc() {
		return sDoc;
	}
}
